package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.OrdersettingDao;
import com.itheima.pojo.OrderSetting;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

@Service
public class OrdersettingServiceImpl implements OrdersettingService {

    @Autowired
    OrdersettingDao ordersettingDao;

    /*
    * 添加ordersetting之前.先判断该日期是否进行预约设置
        如果预约设置过,就修改预约设置
    修改预约设置:判断已预约人数是否大于可预约人数.大于,不可修改,抛出异常
        如果没有预约设置,添加预约设置
    * */
    @Override
    public void editOrderSettingList(List<OrderSetting> orderSettingList) {
        if (orderSettingList != null && orderSettingList.size() > 0) {
            for (OrderSetting orderSetting : orderSettingList) {
                //先判断该日期是否进行预约设置
                OrderSetting orderSettingDB = ordersettingDao.findOrderSettingByDate(orderSetting.getOrderDate());
                if (orderSettingDB == null) {
                    // 没有预约设置,添加预约设置
                    ordersettingDao.add(orderSetting);
                } else {
                    //如果预约设置过,修改
                    //获取已预约人数
                    int reservations = orderSettingDB.getReservations();
                    //获取可预约人数
                    int number = orderSetting.getNumber();
                    if (number >= reservations) {
                        ordersettingDao.edit(orderSetting);
                    } else {
                        //大于,不可修改,抛出异常
                        throw new RuntimeException("已预约人数大于可以预约的人数,批量导入失败");
                    }
                }
            }
        }
    }

    @Override
    public List<OrderSetting> fingByMonth(String month) {
        String firstDay = month + "-01";
        String lastDay = month + "-31";
        List<OrderSetting> ordersettingList = ordersettingDao.findOrderSettingsByDate(firstDay,lastDay);
        return ordersettingList;
    }

    @Override
    public void clear() {
        try {
            String date = DateUtils.parseDate2String(new Date());
            ordersettingDao.clear(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
